/**
  author: tangke
 */

package main

import (
	"os"
	"flag"
	"fmt"
	"supplychain/sdkInit"
	"supplychain/service"
	"supplychain/web"
	"supplychain/web/controller"
)

const (
	initialized = false
	SimpleCC = "simplecc"
)

func main() {
	

	port := flag.Int("p", 9000, "server port")
	role := flag.String("r", "User1", "client role")
	chaincode := flag.Bool("n", false, "install chaincode or not")
	mycc := flag.String("c", SimpleCC, "chaincode name")
	flag.Parse()

	configFile := os.Getenv("GOPATH") + "/src/supplychain/config.yaml"

	initInfo := &sdkInit.InitInfo{

		ChannelID: "mychannel",
		//ChannelConfig: "/home/tangke/mygithub/fabric-samples/first-network/channel-artifacts/channel.tx",
		ChannelConfig: os.Getenv("GOPATH") + "/src/github.com/hyperledger/fabric-samples/first-network/channel-artifacts/channel.tx",

		OrgAdmin:"Admin",
		OrgName:"Org1",
		OrdererOrgName: "orderer.example.com",

		ChaincodeID: SimpleCC,
		ChaincodeGoPath: os.Getenv("GOPATH"),
		//ChaincodePath: "tk/mychaincode/supplychain_test/chaincode/supplychaincode",
		ChaincodePath: "supplychain/chaincode/supplychaincode",
		UserName:"User1",
	}

	initInfo.UserName = *role
	initInfo.ChaincodeID = *mycc

	sdk, err := sdkInit.SetupSDK(configFile, initialized)
	if err != nil {
		fmt.Printf(err.Error())
		return
	}

	defer sdk.Close()

	err = sdkInit.CreateChannel(sdk, initInfo)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	channelClient, err := sdkInit.InstallAndInstantiateCC(sdk, initInfo, *chaincode)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println(channelClient)

	//===========================================//

	serviceSetup := service.ServiceSetup{
		ChaincodeID:initInfo.ChaincodeID,
		Client:channelClient,
	}

	/*
	msg, err := serviceSetup.SetOrder("a", "1")
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(msg)
	}
	*/

	/*
	msg, err = serviceSetup.GetInfo("a")
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(msg)
	}*/

	//===========================================//

	app := controller.Application{
		Fabric: &serviceSetup,
	}
	web.WebStart(&app, *port)

}
